package com.itheima.service.oders.impl;

import com.github.pagehelper.PageHelper;
import com.itheima.domain.Orders;
import com.itheima.factory.MapperFactory;
import com.itheima.mapper.login.LoginMapper;
import com.itheima.mapper.orders.OrdersMapper;
import com.itheima.service.oders.OrdersService;
import com.itheima.utils.TransactionUtil;
import com.sun.org.apache.xpath.internal.operations.Or;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.ByteArrayOutputStream;
import java.util.List;

public class OrdersServiceImpl implements OrdersService {
    /**
     * 查询所有订单-产品
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public List<Orders> findAll(String pageNum, String pageSize) {
        SqlSession sqlSession = null;
        try{
            //获取SqlSession
            sqlSession = MapperFactory.getSqlSession();
            //获取Mapper
            OrdersMapper mapper = MapperFactory.getMapper(sqlSession, OrdersMapper.class);
            //调用Mapper层操作
            //定义起始页面为1
            int pageN=1;
            //定义每页显示条目数为5
            int pageS=5;
            //处理页面
            if (StringUtils.isNoneBlank(pageNum)){
                pageN = Integer.parseInt(pageNum);
            }
            if (StringUtils.isNoneBlank(pageSize)){
                pageS = Integer.parseInt(pageSize);
            }
            PageHelper.startPage(pageN, pageS);
            List<Orders> list = mapper.findAll();
            //返回
            return list;
        }catch (Exception e){
            //失败 回滚事务
            TransactionUtil.rollback(sqlSession);
            throw new RuntimeException(e);
            //记录日志
        }finally {
            try {
                //提交事务
                TransactionUtil.close(sqlSession);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    /**
     * 删除orders关联的表
     * @param ids
     */
    @Override
    public void deleteByOIds(String ids) {
        SqlSession sqlSession = null;
        //设定默认标记为true

        try{
            //获取SqlSession
            sqlSession = MapperFactory.getSqlSession();
            //获取Mapper
            OrdersMapper mapper = MapperFactory.getMapper(sqlSession, OrdersMapper.class);
            //调用Mapper层操作
            //对ID处理
            String[] id = ids.split(",");
                mapper.deleteByOIds(id);

            //提交事务
            TransactionUtil.commit(sqlSession);
        }catch (Exception e){
            //失败 回滚事务
            TransactionUtil.rollback(sqlSession);
            throw new RuntimeException(e);
            //记录日志
        }finally {
            try {
                //释放资源
                TransactionUtil.close(sqlSession);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    /**
     * 删除orders
     * @return
     */
    @Override
    public boolean deleteByIds(String ids) {
        SqlSession sqlSession = null;
        //设定默认标记为false
        boolean flag = false;
        try{
            //获取SqlSession
            sqlSession = MapperFactory.getSqlSession();
            //获取Mapper
            OrdersMapper mapper = MapperFactory.getMapper(sqlSession, OrdersMapper.class);
            //调用Mapper层操作
            //对ID处理
            String[] id = ids.split(",");

            mapper.deleteByIds(id);
            //提交事务
            TransactionUtil.commit(sqlSession);
            //修改标记为true
            flag = true;

        }catch (Exception e){
            //失败 回滚事务
            TransactionUtil.rollback(sqlSession);
            throw new RuntimeException(e);
            //记录日志
        }finally {
            try {
                //释放资源
                TransactionUtil.close(sqlSession);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return flag;
    }

    /**
     * 模糊查询
     * @param pageNum
     * @param pageSize
     * @param name
     * @return
     */
    @Override
    public List<Orders> findAllByName(String pageNum, String pageSize, String name) {
        SqlSession sqlSession = null;
        try{
            //获取SqlSession
            sqlSession = MapperFactory.getSqlSession();
            //获取Mapper
            OrdersMapper mapper = MapperFactory.getMapper(sqlSession, OrdersMapper.class);
            //调用Mapper层操作
            //定义起始页面为1
            int pageN=1;
            //定义每页显示条目数为5
            int pageS=5;
            //处理页面
            if (StringUtils.isNoneBlank(pageNum)){
                pageN = Integer.parseInt(pageNum);
            }
            if (StringUtils.isNoneBlank(pageSize)){
                pageS = Integer.parseInt(pageSize);
            }
            PageHelper.startPage(pageN, pageS);
            List<Orders> list = mapper.findAllByName(name);
            //返回
            return list;
        }catch (Exception e){
            //失败 回滚事务
            TransactionUtil.rollback(sqlSession);
            throw new RuntimeException(e);
            //记录日志
        }finally {
            try {
                //提交事务
                TransactionUtil.close(sqlSession);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    /**
     * 订单详情
     * @return
     */
    @Override
    public List<Orders> findById(String id) {
        SqlSession sqlSession = null;

        try {
            //获取SqlSession
            sqlSession = MapperFactory.getSqlSession();
            //获取Mapper
            OrdersMapper mapper = MapperFactory.getMapper(sqlSession, OrdersMapper.class);
            //调用Mapper层操作
            List<Orders> orders = mapper.findById(id);
            System.out.println(orders);
            //提交事务
            TransactionUtil.commit(sqlSession);
            return orders;
        } catch (Exception e) {
            //失败 回滚事务
            TransactionUtil.rollback(sqlSession);
            throw new RuntimeException(e);
            //记录日志
        } finally {
            try {
                //释放资源
                TransactionUtil.close(sqlSession);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

    @Override
    public ByteArrayOutputStream getReport() throws Exception{
        SqlSession sqlSession = null;
        List<Orders> orders = null;
        try {
            //获取SqlSession
            sqlSession = MapperFactory.getSqlSession();
            //获取Mapper
            OrdersMapper mapper = MapperFactory.getMapper(sqlSession, OrdersMapper.class);
            //调用Mapper层操作
            orders = mapper.findAll();

            //提交事务
            TransactionUtil.commit(sqlSession);

        } catch (Exception e) {
            //失败 回滚事务
            TransactionUtil.rollback(sqlSession);
            throw new RuntimeException(e);
            //记录日志
        } finally {
            try {
                //释放资源
                TransactionUtil.close(sqlSession);
            } catch (Exception e) {
                e.printStackTrace();
            }
            //1.获取到对应的Excel文件，工作簿文件
            Workbook wb = new XSSFWorkbook();

            //2.创建工作表
            Sheet s = wb.createSheet("订单");

            //设置通用配置
//        s.setColumnWidth(4,100);
            CellStyle cs_field = wb.createCellStyle();
            cs_field.setAlignment(HorizontalAlignment.CENTER);
            cs_field.setBorderTop(BorderStyle.THIN);
            cs_field.setBorderBottom(BorderStyle.THIN);
            cs_field.setBorderLeft(BorderStyle.THIN);
            cs_field.setBorderRight(BorderStyle.THIN);

            //制作标题
            s.addMergedRegion(new CellRangeAddress(1, 1, 1, 6));

            Row row_1 = s.createRow(1);
            Cell cell_1_1 = row_1.createCell(1);
            cell_1_1.setCellValue("订单");

            //创建一个样式
            CellStyle cs_title = wb.createCellStyle();
            cs_title.setAlignment(HorizontalAlignment.CENTER);
            cs_title.setVerticalAlignment(VerticalAlignment.CENTER);
            cell_1_1.setCellStyle(cs_title);

            //制作表头
            String[] fields = {"订单ID", "订单编号", "产品名称", "金额", "下单时间",
                    "订单状态"};
            Row row_2 = s.createRow(2);

            for (int i = 0; i < fields.length; i++) {
                Cell cell_2_temp = row_2.createCell(1 + i); //++
                cell_2_temp.setCellValue(fields[i]);    //++
                cell_2_temp.setCellStyle(cs_field);
            }
            //设置时间列宽
            s.setColumnWidth(1, 10000);
            s.setColumnWidth(3, 5000);
            s.setColumnWidth(4, 5000);
            s.setColumnWidth(5, 7000);

            //制作数据区
            int row_index = 0;
            for (Orders order : orders) {
                int cell_index = 0;
                Row row_temp = s.createRow(3 + row_index++);

                Cell cell_data_1 = row_temp.createCell(1 + cell_index++);
                cell_data_1.setCellValue(order.getId());    //++
                cell_data_1.setCellStyle(cs_field);

                Cell cell_data_2 = row_temp.createCell(1 + cell_index++);
                cell_data_2.setCellValue(order.getOrderNum());    //++
                cell_data_2.setCellStyle(cs_field);

                Cell cell_data_3 = row_temp.createCell(1 + cell_index++);
                cell_data_3.setCellValue(order.getProduct().getProductName());    //++
                cell_data_3.setCellStyle(cs_field);

                Cell cell_data_4 = row_temp.createCell(1 + cell_index++);
                cell_data_4.setCellValue(order.getProduct().getProductPrice());    //++
                cell_data_4.setCellStyle(cs_field);

                Cell cell_data_5 = row_temp.createCell(1 + cell_index++);
                cell_data_5.setCellValue(order.getOrderTimeStr());    //++
                cell_data_5.setCellStyle(cs_field);

                Cell cell_data_6 = row_temp.createCell(1 + cell_index++);
                cell_data_6.setCellValue(order.getOrderStatus()==1?"已下单":"待付款");    //++
                cell_data_6.setCellStyle(cs_field);



            }

            //将内存中的workbook数据写入到流中
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            wb.write(os);
            wb.close();
            return os;
        }
    }


}
